package tue.cse.advanceddatabases.project;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.faces.context.FacesContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class MusicEngineBean {
	private static final Logger logger = Logger.getLogger(MusicEngineBean.class
            .getName());
	private static final String HOST = "http://localhost:8080/exist/rest";
	private static final String COLLECTION = HOST + "/Test1/";
	private static final String XQL_COLLECTION = "http://localhost:8080/exist/ad/";

	private HttpClient _client;
	
	//Goran: add status
	protected String status = null;
	private boolean isNew = true;
	
	public MusicEngineBean(){
        _client = new HttpClient(new MultiThreadedHttpConnectionManager());
        _client.getHttpConnectionManager().
            getParams().setConnectionTimeout(30000);		
	}

	public String getStatus() {
	        return status;
	}
	public void setStatus(String newStatus) {
	        status = newStatus;
	}
	    
	public boolean getIsNew() {
		return isNew;
	}
	public void setIsNew(boolean isNew) {
		this.isNew = isNew;
	}

	protected String queryBegin() {
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<query xmlns=\"http://exist.sourceforge.net/NS/exist\" "
				+ "start=\"1\" max=\"5\">" + "<text>"; 
	}
	
	protected String queryEnd() {
		return "</text>" + "<properties>"
				+ "<property name=\"indent\" value=\"yes\"/>" + "</properties>"
				+ "</query>";
	}
	
	protected String updateBegin(){
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + 
		"<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">";
	}
	
	protected String updateEnd(){
		return "</xu:modifications>";		
	}
	
	public String executeQueryXQL(String queryName, NameValuePair[] parameters){
		GetMethod get = new GetMethod(XQL_COLLECTION + queryName);
		
		if (parameters !=null)
			get.setQueryString(parameters);

		try {
			int iGetResultCode = _client.executeMethod(get);
			return  get.getResponseBodyAsString();
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
		
	}
	
	@SuppressWarnings("deprecation")
	public String executeQuery(String aQuery, String aDocument){

		PostMethod post = new PostMethod(COLLECTION + aDocument);
		post.setRequestHeader("Content-Type","text/xml");

		try {
			StringRequestEntity sre = new StringRequestEntity(aQuery,"text/xml","UTF-8");
			post.setRequestEntity(sre);
			
			logger.info("The query is:\n" + aQuery);
			
			int iGetResultCode = _client.executeMethod(post);
			return  post.getResponseBodyAsString();
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		return "fail";
		//return "top tracks";
	}
	
	/** return the ROOT element of the XML String **/
	protected Element stringToXml(String xmlResult){
		try {
			org.dom4j.Document document = DocumentHelper.parseText(xmlResult);
			return document.getRootElement();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	
	/** remove root node, which contains existDB info **/
	protected List<Element> removeExistDBElement(String xmlResult){
		try {
			org.dom4j.Document document = DocumentHelper.parseText(xmlResult);
			//We must remove the root element, because it contains the ExistDB element
			Element rootElement = document.getRootElement();
			if (rootElement != null){
				List<Element> children = rootElement.elements();
				if (children != null){
					return children;
				}
			}
			
		} catch (DocumentException e) {
			return null;
		}
		
		return null;
	}
	
	/** get the "albumKey" of the request parameters **/
	protected String getAlbumKey() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return (String) facesContext.getExternalContext().getRequestParameterMap().get("albumKey");
	}
	
	/** get the "artistKey" of the request parameters **/
	protected String getArtistKey() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return (String) facesContext.getExternalContext().getRequestParameterMap().get("artistKey");
	}
	
	/** get the "trackKey" of the request parameters **/
	protected String getTrackKey() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return (String) facesContext.getExternalContext().getRequestParameterMap().get("trackKey");
	}
}

